/*
 * Created by 岱青海蓝信息系统(北京)有限公司 on 17-6-15 下午1:30
 * Copyright (c) 2017. All rights reserved.
 */

package com.example.dqhl.jdmetro.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.example.dqhl.jdmetro.R;
import com.example.dqhl.jdmetro.activities.AboutJDMetroActivity;
import com.example.dqhl.jdmetro.activities.MyCallBackActivity;
import com.example.dqhl.jdmetro.activities.MyCollectionActivity;
import com.example.dqhl.jdmetro.activities.MyInfoActivity;
import com.example.dqhl.jdmetro.activities.SettingActivity;
import com.example.dqhl.jdmetro.base.BaseFragment;
import com.example.dqhl.jdmetro.bean.User;
import com.example.dqhl.jdmetro.config.Config;
import com.example.dqhl.jdmetro.config.Constant;
import com.example.dqhl.jdmetro.utils.Dlog;
import com.example.dqhl.jdmetro.utils.JsonUtils;
import com.example.dqhl.jdmetro.utils.JumpItent;
import com.example.dqhl.jdmetro.utils.MyCallBackTakePhoto;
import com.example.dqhl.jdmetro.utils.Toastutils;
import com.example.dqhl.jdmetro.utils.UserSaveUtil;
import com.example.dqhl.jdmetro.view.CircleImageView;
import com.example.dqhl.jdmetro.view.PictureSelectPopupWindow;
import com.jph.takephoto.model.TResult;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * description:个人中心
 * autour:guanluocang
 * date:17/6/15 13:31
 */
public class PersonalFragment extends BaseFragment {

    private Context context;
    @Bind(R.id.personal_info)//父布局
    LinearLayout personal_info;
    @Bind(R.id.ll_myMessage)//我的消息
            LinearLayout ll_myMessage;
    @Bind(R.id.ll_myCollect)//我的收藏
            LinearLayout ll_myCollect;
    @Bind(R.id.ll_aboutJd)//关于京东新城
            LinearLayout ll_aboutJd;
    @Bind(R.id.ll_mySetting)//设置
            LinearLayout ll_mySetting;
    @Bind(R.id.ll_myCallback)//意见反馈
            LinearLayout ll_myCallback;
    @Bind(R.id.iv_topImg)
    CircleImageView iv_topImg;

    private MyCallBackTakePhoto takePhoto;
    private PictureSelectPopupWindow pictureSelectPopupWindow;
    private String headPortraitPath = "";//头像地址

    @Override
    public View initView(LayoutInflater inflater) {
        rootView = inflater.inflate(R.layout.fragment_personal, null);
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popupwindow_pic_select, null);
        takePhoto = MyCallBackTakePhoto.of(contentView);
        context = getActivity();
        ButterKnife.bind(this, rootView);
        initTitleBar(rootView, R.string.txt_personal);
        setLeftBackVisibility(rootView, View.GONE);
        registerBroadcastReceiver();
        return rootView;
    }


    /**
     * 广播接收者
     */
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case Constant.ACTION_LOGIN_SUCCESS:
                    user = (User) intent.getExtras().get("user");
                    initData();
                    break;
                case Constant.ACTION_LOGOUT_SUCCESS:
                    user = null;
                    initData();
                    break;
            }
        }
    };

    /**
     * 注册广播接收着
     */
    private void registerBroadcastReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_LOGIN_SUCCESS);
        intentFilter.addAction(Constant.ACTION_LOGOUT_SUCCESS);
        context.registerReceiver(receiver, intentFilter);
    }

    @Override
    public void initData() {
        pictureSelectPopupWindow = new PictureSelectPopupWindow(getActivity(), pictureSelectItemsOnClick);
        pictureSelectPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                pictureSelectPopupWindow.backgroundAlpha(1.0f);
            }
        });
        if (user != null) {
            x.image().bind(iv_topImg, Config.pic_base_url + user.getPhoto());
        } else {
            iv_topImg.setImageResource(R.drawable.ic_default);
        }

    }

    //头像选择 Pop 点击事件
    View.OnClickListener pictureSelectItemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.btn_take_photo:   // 调用系统相机
                    takePhoto.onClick(view, getTakePhoto());
                    pictureSelectPopupWindow.dismiss();
                    break;
                case R.id.btn_pick_photo:   // 调取手机相册
                    takePhoto.onClick(view, getTakePhoto());
                    pictureSelectPopupWindow.dismiss();
                    break;
                case R.id.btn_cancel:   // 取消
                    pictureSelectPopupWindow.dismiss();
                    break;
            }
        }
    };

    @Override
    public void initListener() {
        ll_aboutJd.setOnClickListener(this);
        ll_myCollect.setOnClickListener(this);
        ll_myCallback.setOnClickListener(this);
        ll_myMessage.setOnClickListener(this);
        ll_mySetting.setOnClickListener(this);
        iv_topImg.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //我的消息
            case R.id.ll_myMessage:
                if (user != null) {
                    JumpItent.jump(getActivity(), MyInfoActivity.class);
                } else {
                    Toastutils.show("请先登录");
                }
                break;
            //我的收藏
            case R.id.ll_myCollect:
                if (user != null) {
                    JumpItent.jump(getActivity(), MyCollectionActivity.class);
                } else {
                    Toastutils.show("请先登录");
                }
                break;
            //关于京东新城
            case R.id.ll_aboutJd:
                JumpItent.jump(getActivity(), AboutJDMetroActivity.class);
                break;
            //设置
            case R.id.ll_mySetting:
                JumpItent.jump(getActivity(), SettingActivity.class);
                break;
            //反馈
            case R.id.ll_myCallback:
                if (user != null) {
                    JumpItent.jump(getActivity(), MyCallBackActivity.class);
                } else {

                }
                break;
            //修改头像
            case R.id.iv_topImg:
                if(user != null){
                    pictureSelectPopupWindow.showAtLocation(personal_info, Gravity.BOTTOM, 0, 0);
                    pictureSelectPopupWindow.backgroundAlpha(0.5f);
                }else{
                    Toastutils.show("请先登录");
                }

                break;
        }

    }

    @Override
    public void takeCancel() {
        super.takeCancel();
    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        Dlog.e("GG" + result.getImage().getCompressPath());
        headPortraitPath = result.getImage().getCompressPath();
        // 更换头像的操作
        updateHeadPortrait();
    }
    //更换头像

    public void updateHeadPortrait() {
        File head_img = new File(headPortraitPath);
        if (head_img.isFile()) {
            RequestParams params = new RequestParams(Config.updata_logo);
            params.addBodyParameter("id_auth", user.getId_auth());
            params.addBodyParameter("photo", head_img);
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Dlog.e(result);
                    int errCode = JsonUtils.getErrCode(result);
                    String errMsg = JsonUtils.getErrMsg(result);
                    String data = JsonUtils.getData(result);
                    if (errCode == 200) {
                        String head = JsonUtils.getInfo(data, "photo");
                        Dlog.e("GG" + head);
                        user.setPhoto(head);
                        x.image().bind(iv_topImg, headPortraitPath);
                        UserSaveUtil.saveUser(getActivity(), user);
                    }


                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    Dlog.e(ex + "");
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    Dlog.e("finish");
                }
            });
        } else {
            Toastutils.show("不是图片文件");
        }


    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        if (receiver != null) {
            context.unregisterReceiver(receiver);
        }
    }
}
